package service

import (
	"fmt"
	"math/rand"
	"time"
	"waimai/dao"
	"waimai/model"
	"waimai/param"
	"waimai/tool"
)

type MemberServie struct {

}

func (s *MemberServie) SmsLogin(loginparam param.SmsLoginParam)*model.Member{
	//获取手机号和验证码
	//验证手机号码是否正确
	md :=dao.MemberDao{tool.DbEngine}
	sms:=md.ValidateSmsCode(loginparam.Phone,loginparam.Code)
	if sms.Id==0{
		return nil
	}
	//根据手机号查询记录
	member:=md.QueryByPhone(loginparam.Phone)
	if member.Id!=0{
		return member
	}
	//创建一个member
	user:=model.Member{}

	user.UserName	=loginparam.Phone
	user.Mobile		=loginparam.Phone
	user.RegisterTime=time.Now().Unix()
	user.Id 		= md.InsertMember(user)

	return &user
}

func(s *MemberServie)SendCode(phone string)bool{
	//生成二维码
	code:=fmt.Sprintf("%06v",rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	//调用sdk
	//config:=tool.GetConfig().Sms
	//
	//client, err := dysmsapi.NewClientWithAccessKey(config.RegionId,config.AppKey, config.AppSecret)
	//if err != nil {
	//	fmt.Print(err.Error())
	//	return false
	//}
	//request := dysmsapi.CreateSendSmsRequest()
	//request.Scheme = "https"
	//request.SignName = config.SignName
	//request.TemplateCode = config.TemplateCode
	//request.PhoneNumbers =	phone
	//par,err:=json.Marshal(map[string]interface{}{
	//	"code":code,
	//})
	//request.TemplateParam =	string(par)
	//response, err := client.SendSms(request)
	//
	//if err != nil {
	//	fmt.Print(err.Error())
	//	return false
	//}
	//if response.Code=="OK"{
	if true{
		smsCode:=model.SmsCode{
			Phone:phone,
			BizId: "成功",
			Code:code,
			CreateTime: time.Now().Unix(),
		}

		memberDao:=dao.MemberDao{tool.DbEngine}

		result :=memberDao.InsertCode(&smsCode)

		return result>0
	}else{
		return false
	}


}

func (s *MemberServie)Login(name string,password string)*model.Member{
	md :=dao.MemberDao{tool.DbEngine}
	//根据手机号查询member表记录
	member:=md.Query(name,password)
	if member.Id!=0{
		if member.Password!=password{
			return nil
		}else{
			return member
		}
	}
	//用户不存在的时候
	user:=model.Member{}
	user.UserName=name
	user.Password=password
	user.RegisterTime=time.Now().Unix()
	result:=md.InsertMember(user)
	user.Id=result
	return member

}
